<?php

namespace App\Transformers;

use App\Models\News;
use App\Models\NewsCollects;
use App\Models\NewsLike;

class NewsTransformer extends BaseTransformer
{
    protected $availableIncludes = ['comments'];

    private $user;

    public function __construct(array $select = [], $user = null)
    {
        $this->user = $user;

        parent::__construct($select);
    }

    public function transform(News $model)
    {
        return [
            'id' => $model->id,
            'user_id' => $model->object_id,
            'user_nick_name' => $model->object->nick_name ?: $model->object->username,
            'user_nick_avatar' => image_url($model->object->avatar),
            'role' => getModelName($model->object_type),
            'title' => $model->title,
            'subtitle' => $model->subtitle,
            'front_cover' => image_url($model->front_cover),
            'content' => $model->content,
            'view_amount' => $model->view_amount,
            'like_amount' => $model->like_amount,
            'collect_amount' => $model->collect_amount,
            'sort' => $model->sort,
            'is_show' => $model->is_show,
            'is_likes' => $this->isLike($model->id),
            'is_collect' => $this->isCollect($model->id),
            'created_at' => $model->created_at->toDateTimeString(),
        ];
    }

    public function includeComments(News $model)
    {
        return $this->collection($model->comments->where('is_show', true), new CommentTransformer([], $this->user));
    }

    public function isLike($news_id)
    {
        $result = false;

        if ($this->user) {
            $result = !!NewsLike::where('news_id', $news_id)->where('user_id', $this->user->id)->first();
        }

        return $result;
    }

    public function isCollect($news_id)
    {
        $result = false;

        if ($this->user) {
            $result = !!NewsCollects::where('news_id', $news_id)->where('user_id', $this->user->id)->first();
        }

        return $result;
    }
}
